<template>
	<view>
		 <text style = "font-size:25px;">计数器: {{ counter }}</text>
		  <button @click = "counter++" style = "font-size:25px;">点我</button>
	</view>
</template>

<script>
	
	export default {
		data() {
			return {
				 counter: 1,
				name: "kirin",
				obj: {
					age: 18,
					sex: "man"
				}
			}
		},
		onLoad(){
			
			// async function testAsync() {
			//     return "hello async";
			// }
			
			// const result = testAsync(); // 返回一个Promise对象
			// console.log("666",result);
			// result.then(s=>{
			// 	console.log(s);
			// });
			// testAsync().then(v => {
			//     console.log(v);    // 输出 hello async
			// });
			
			
		},
		onShow(){
			// 像普通函数调用async函数，在then函数中获取整个流程的返回信息，在catch函数统一处理出错信息
			this.asyncFunction().then(data => {
			    console.log(data);       // asyncFunction return 的内容在这里获取
			}).catch(error => {
			    console.log(error);      // asyncFunction 的错误统一在这里抓取
			});
			
			console.log('after asyncFunction code executing....'); // 这个代表asyncFunction函数后的代码，                                                     // 显示asyncFunction本身会立即返回，不会阻塞主线程
		},
		
		watch: {
			counter:function(newValue,oldValue){
				console.log("之前的值："+oldValue+"之后的值："+newValue);
			}
		},
		methods: {
			// 异步过程封装
			async sleep(ms) {
			    return new Promise((resolve) => {
			        setTimeout(() => {
			            resolve('sleep for ' + ms + ' ms');
			        }, ms);
			    });
			},
			async asyncFunction() {
			    console.time('asyncFunction total executing:');
			    const sleep1 = await this.sleep(2000);
			    console.log('sleep1: ' + sleep1);
			    const [sleep2, sleep3, sleep4]= await Promise.all([this.sleep(2000), this.sleep(1000), this.sleep(1500)]);
			    console.log('sleep2: ' + sleep2);
			    console.log('sleep3: ' + sleep3);
			    console.log('sleep4: ' + sleep4);
			    const sleepRace = await Promise.race([this.sleep(3000), this.sleep(1000), this.sleep(1000)]);
			    console.log('sleep race: ' + sleepRace);
			    console.timeEnd('asyncFunction total executing:');
			    
			    return 'asyncFunction done.'  // 这个可以不返回，这里只是做个标记，为了显示流程
			}
		},
		
	}
</script>
